import 'dart:math';

import 'package:demo/pages/goods_detail.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

class GoodsList extends StatefulWidget {
  const GoodsList({super.key});

  @override
  State<GoodsList> createState() => _GoodsListState();
}

class _GoodsListState extends State<GoodsList> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.amberAccent,
          title: Text('美团外卖'),
        ),
        body: CustomDio(),
      );
  }
}

// dio网络请求
// 发请求需要在恰当时机，依赖生命周期(有状态组件)
class CustomDio extends StatefulWidget {
  const CustomDio({super.key});

  @override
  State<CustomDio> createState() => _CustomDioState();
}

class _CustomDioState extends State<CustomDio> {
  // 生命周期
  @override
  void initState() {
    // 调用父类的周期
    super.initState();
    // 调用请求方法
    getData();
  }

  // 定义一个数据
  List list = [];

  // 使用dio发送请求的方法
  getData() async {
    // 1.创建dio请求示例
    final dio = Dio();
    // 2.发送请求
    Response res = await dio.get(
      'https://zhousg.atomgit.net/harmonyos-next/takeaway.json',
    );

    setState(() {
      // 将结果转成字符串
      // result = res.data.toString();
      // 取出数据的某个字段，只能用['key']不能.
      list = res.data;
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
      // 循环分类
      itemBuilder: (context, index) {
        return Padding(
          padding: EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(list[index]['name']),
              CustomList(listItem: list[index]),
            ],
          ),
        );
      },
      separatorBuilder: (context, index) {
        return Container(height: 8, color: Colors.transparent);
      },
      itemCount: list.length,
    );
  }
}

// 基础组件
class CustomList extends StatefulWidget {
  final Map listItem;
  const CustomList({super.key, required this.listItem});

  @override
  State<CustomList> createState() => _CustomListState();
}

// 实现接收数据
class _CustomListState extends State<CustomList> {
  Map listItem = {};
  @override
  void initState() {
    super.initState();
    listItem = widget.listItem;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 1.可以执行for循环生成重复的结构体(不加大括号)
        for (int i = 0; i < listItem['foods'].length; i++)
          SizedBox(
            child:
            // 路由跳转
            // 每一个菜品
            GestureDetector(
              onTap: () {
                // 第一种：直接跳转路由
                // Navigator.push(
                //   context,
                //   MaterialPageRoute(
                //     builder: (context) {
                //       return GoodsDetail();
                //     },
                //   ),
                // );
                // 第二种：配置命名路由(给web端做适配)
                // 传递路由参数
                Navigator.pushNamed(context,'/detail',arguments: {'name':'张三${Random().nextInt(10)}'});
              },
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: EdgeInsets.all(8),
                    child: Image.network(
                      listItem['foods'][i]['picture'],
                      width: 80,
                      height: 80,
                      fit: BoxFit.cover,
                    ),
                  ),
                  Expanded(
                    flex: 1,
                    child: Padding(
                      padding: EdgeInsets.all(8),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(listItem['foods'][i]['name']),
                          //2.可以执行if条件渲染生成结构体(不加大括号)
                          if (listItem['foods'][i]['description'].length != 0)
                            Text(listItem['foods'][i]['description']),
                          if (listItem['foods'][i]['food_tag_list'].length != 0)
                            Text(listItem['foods'][i]['food_tag_list'][0]),
                          Text(
                            '月销售${listItem['foods'][i]['month_saled']} ${listItem['foods'][i]['like_ratio_desc']}',
                          ),
                          Row(
                            children: [
                              Text.rich(
                                TextSpan(
                                  children: [
                                    TextSpan(text: '￥'),
                                    TextSpan(
                                      text:
                                          listItem['foods'][i]['price']
                                              .toString(),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
      ],
    );
  }
}
